use crate::app::node_item::NodeItemUI;
use crate::app::UIComponent;
use crate::data::{ANode, Node};
use crate::types::NodeType;
use eframe::egui;
use eframe::egui::Ui;
use std::sync::Arc;

pub struct NodeListUI {}

impl NodeListUI {
    pub fn new() -> NodeListUI {
        NodeListUI {}
    }

    fn draw(ui: &mut Ui, node: ANode, layer: f32, curr_id: u32) {
        let response = ui.add(NodeItemUI::new(Arc::clone(&node), curr_id, layer));
        if response.clicked() {
            Node::set_current_node(ui.ctx(), Arc::clone(&node));
        }
        if let Ok(_node) = node.try_lock() {
            if !_node.is_expand {
                // 绘制子节点内容
                for child in _node.children.iter() {
                    Self::draw(ui, Arc::clone(child), layer + 1.0, curr_id);
                }
            }
        }
    }
}

impl UIComponent for NodeListUI {
    fn update(&mut self, ui: &mut Ui) {
        // 文件列表
        egui::SidePanel::left(ui.next_auto_id())
            .resizable(true)
            .default_width(200.)
            .min_width(100.)
            .max_width(500.)
            .show_inside(ui, |ui| {
                ui.vertical_centered_justified(|ui| {
                    let curr_node = Node::get_current_node(ui.ctx());
                    let (curr_id, title) = if let Ok(curr_node) = curr_node.try_lock() {
                        let is_condition = match curr_node.node_type.value {
                            NodeType::Leaf(is_condition) => {
                                is_condition
                            }
                            NodeType::Composite(_, is_condition) => {
                                is_condition
                            }
                        };
                        let title = if is_condition { "条件树" } else { "动作树" };
                        (curr_node.id, title)
                    } else { (0, "") };
                    ui.heading(format!("节点列表:{title}"));
                    let root_node = Node::get_list_root_node(ui.ctx());
                    Self::draw(ui, root_node, 0.0, curr_id);
                });
            });
    }
}
